home *** CD-ROM | disk | FTP | other *** search
- Path: news.umbc.edu!not-for-mail
- From: schlein@umbc.edu (Jonas J. Schlein)
- Newsgroups: comp.lang.c
- Subject: Re: Type casting
- Date: 29 Feb 1996 17:52:06 -0500
- Organization: University of Maryland Baltimore County
- Message-ID: <4h5amm$dpv@umbc9.umbc.edu>
- References: <4gfnmi$gsc@calvin.risq.qc.ca>
- NNTP-Posting-Host: umbc9.umbc.edu
- NNTP-Posting-User: schlein
-
- Pierre Coulombe <pcoulomb@criq.qc.ca> wrote:
- |> I have a problem with type casting in Visual C 1.5.
- |> I expected the following program to print the value 254 for valI.
- |> Instead it gives the output shown below.
- |> Can someone tell me where is my mistake ?
- |>
- |>
- |> ******** Program *********
- |>
- |> #include <stdio.h>
- |> #include <string.h>
- |> #include <stdlib.h>
- |>
- |> typedef unsigned int UINT;
- |>
- |> #define MM_TO_UNITS 10.0F
- |>
- |> void main(void)
-
- That's a no-no on c.l.c...Please read the FAQ and then you will fully
- understand why for your program a correct definition is 'int main (void)'.
-
- |> {
- |> float valF;
- |> UINT valI;
- |> char string[80];
- |>
- |> strcpy(string, "25.4");
- |>
- |> valI = (UINT) ((float) atof(string) * MM_TO_UNITS);
-
- Maybe if you used doubles your problem would go away and maybe not.
- Try to write 0.4 out in binary and you'll probably have a hard time
- or need a lot of bits. So 25.4 may really be 25.3999999... for all
- we know. Type casting will round down for positive numbers.
-
- |> printf("valI = %u\n", valI);
- |>
- |> sprintf(string, "%f", (float) atof(string) * MM_TO_UNITS);
-
- I guess this will work, but I'd be skeptical since you are reading
- from string while also using it for writing. I don't have my references
- near by so just take this as something to think about.
-
- |> printf("string = %s\n", string);
- |>
- |> strcpy(string, "25.4");
- |> sprintf(string, "%u", (UINT) ((float) atof(string) * MM_TO_UNITS));
-
- See two comments up.
-
- |> printf("string = %s\n", string);
- |> }
- |>
- |>
- |> ******** Output *********
- |>
- |> valI = 253
- |> string = 254.000000
- |> string = 253
-
- So basically it's a matter of computer precision. I ran your program as is
- and was unable to reproduce your results on a UNIX platform. However, I
- suspect that is due to floats being a bigger bit size. Just a nitpick, but
- you never use the variable valF in your code although it is declared.
- --
- "If it wasn't for C, we would be using BASI, PASAL, and OBOL."
-
- Jonas J. Schlein (schlein@gl.umbc.edu)
-